//
//  HomeCell6.m
//  Tunnel
//
//  Created by wbb on 2025/6/5.
//

#import "HomeCell7.h"
#import "HyCategories.h"
#import "HyChartsBarDemoCursor.h"
#import "HyCharts.h"
#import "AQJCVC.h"
#import <WebKit/WebKit.h>
@interface HomeCell7()<WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSArray * titles;
@property (nonatomic, copy) NSArray * valuse;
@end
@implementation HomeCell7

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    
}
- (void)cellWithData:(id)data {
    [super cellWithData:data];
    
    NSArray *arr = (NSArray *)data;
    NSMutableArray *values = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *titles = [NSMutableArray arrayWithCapacity:0];

    for (NSInteger i=0; i<arr.count; i++) {
        NSDictionary *dic = arr[i];
        [values addObject:@[
            dic[@"zcs"],dic[@"ycs"],dic[@"ycyzs"]
        ]];
        
        [titles addObject:dic[@"yhDeptName"]?:@""];
    }
    
    [self setDataSource:values titles:titles];
}
- (void)setDataSource:(NSArray *)valuse titles:(NSArray *)titles {
    _titles = titles;
    _valuse = valuse;
//    UIView *oneChartView =  [self twoChartBarViewWithFrame:CGRectMake(15, 0, kSCREEN_WIDTH -30 - 24, ScaleNum(180))];
//    [self.bgView addSubview:oneChartView];
    [self loadWebView];
}
- (void)loadWebView {
    if(self.webView) {
        [self.webView reload];
        return;
    }
    // 初始化WKWebView配置
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    // 创建WKWebView
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(15, 10, kSCREEN_WIDTH -30 - 24, ScaleNum(162)) configuration:config];
    self.webView.navigationDelegate = self;
//    self.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.bgView addSubview:self.webView];
    self.webView.scrollView.scrollEnabled = NO;
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.offset(0);
    }];
    // 加载本地HTML文件（确保HTML文件已添加到项目中，并勾选了对应的target）
    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"BarsetCharts" ofType:@"html"];
    NSURL *fileURL = [NSURL fileURLWithPath:htmlPath];
    NSURLRequest *request = [NSURLRequest requestWithURL:fileURL];
    [self.webView loadRequest:request];
}


- (UIView *)twoChartBarViewWithFrame:(CGRect)frame {
    
    UIView *contentView = [[UIView alloc] initWithFrame:frame];
    contentView.backgroundColor = UIColor.whiteColor;
    contentView.layer.cornerRadius = 5;
    contentView.layer.borderWidth = 1.0;
    contentView.layer.borderColor = UIColor.groupTableViewBackgroundColor.CGColor;
    contentView.clipsToBounds = NO;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, CGRectGetWidth(frame) - 20, 25)];
    titleLabel.text = @"";
    titleLabel.font = [UIFont systemFontOfSize:17];
    titleLabel.textColor = UIColor.darkTextColor;
    [titleLabel sizeToFit];
    [contentView addSubview:titleLabel];
    
    UIView *(^typeView)(UIColor *color , NSString *title) =
    ^UIView * (UIColor *color , NSString *title) {
        UIView *tView = UIView.new;
        
        UIView *colorView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 8, 8)];
        colorView.backgroundColor = color;
        colorView.layer.cornerRadius = 4;
        [tView addSubview:colorView];
        
        UILabel *tLable = UILabel.new;
        tLable.text = title;
        tLable.textColor = hexColor(999999);
        tLable.font = [UIFont systemFontOfSize:14];
        [tLable sizeToFit];
        tLable.left = colorView.right + 3;
        tLable.centerYIsEqualTo(colorView);
        [tView addSubview:tLable];
        
        tView.sizeValue(tLable.right, colorView.height);
        
        return tView;
    };
    
    NSArray<UIColor *> *colorArray = @[hexColor(21B91D), hexColor(F3A642), hexColor(FF3245)];
    UIView *yView = typeView(colorArray.firstObject, @"正常");
    UIView *oView = typeView(colorArray[1], @"异常");
    UIView *mView = typeView(colorArray.lastObject, @"异常且严重");
    [contentView addSubview:yView];
    [contentView addSubview:oView];
    [contentView addSubview:mView];
    yView.centerY = oView.centerY = mView.centerY = titleLabel.centerY;
    yView.left = titleLabel.right + 10;
    oView.left = yView.right + 5;
    mView.left = oView.right + 5;
    
    HyChartBarView *chartBarView =  [[HyChartBarView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(titleLabel.frame) + 15, CGRectGetWidth(contentView.frame) - 20, CGRectGetHeight(frame) - CGRectGetMaxY(titleLabel.frame) - 25)];
    [contentView addSubview:chartBarView];
    
    chartBarView.contentEdgeInsets = UIEdgeInsetsMake(0, 35, 35, 10);
    chartBarView.pinchGestureDisabled = YES;
    
    HyChartsBarDemoCursor *cursor = HyChartsBarDemoCursor.new;
    cursor.showView = chartBarView;
    [chartBarView resetChartCursor:cursor];
    UIView *tagView = [cursor.showView viewWithTag:999];
    [cursor.showView bringSubviewToFront:tagView];
    // 配置坐标轴
    [[chartBarView.dataSource.axisDataSource configXAxisWithModel:^(id<HyChartXAxisModelProtocol>  _Nonnull xAxisModel) {
        xAxisModel.topXaxisDisabled = NO;
        [[[[xAxisModel configNumberOfIndexs:5] configAxisGridLineInfo:^(id<HyChartAxisGridLineInfoProtocol>  _Nonnull axisGridLineInfo) {
            axisGridLineInfo.axisGridLineType = HyChartAxisLineTypeNone;
        }] configBottomXAxisInfo:^(id<HyChartXAxisInfoProtocol>  _Nonnull xAxisInfo) {
//            xAxisInfo.rotateAngle = - M_PI_4;
            xAxisInfo.axisTextFont = [UIFont systemFontOfSize:14];
            xAxisInfo.displayAxisZeroText = NO;
        }] configTopXAxisInfo:^(id<HyChartXAxisInfoProtocol>  _Nonnull xAxisInfo) {
            xAxisInfo.autoSetText = NO;
            xAxisInfo.axisLineWidth = 1;
            xAxisInfo.axisLineColor = UIColor.groupTableViewBackgroundColor;
        }];
    }] configYAxisWithModel:^(id<HyChartYAxisModelProtocol>  _Nonnull yAxisModel) {
        
        [[[yAxisModel configNumberOfIndexs:5] configYAxisMaxValue:^NSNumber * _Nonnull{
            return @20;
        }] configLeftYAxisInfo:^(id<HyChartYAxisInfoProtocol>  _Nonnull yAxisInfo) {
            yAxisInfo.axisTextFont = [UIFont systemFontOfSize:14];
            yAxisInfo.axisTextPosition = HyChartAxisTextPositionBinus;
            yAxisInfo.axisLineType = HyChartAxisLineTypeNone;
            yAxisInfo.displayAxisZeroText = NO;
        }];
    }];
    
    // 配置图表信息
    [chartBarView.dataSource.configreDataSource configConfigure:^(id<HyChartBarConfigureProtocol>  _Nonnull configure) {
        configure.width = 24;
        configure.autoMargin = YES;
        [configure configBarConfigureAtIndex:^(NSInteger index, id<HyChartBarOneConfigureProtocol>  _Nonnull oneConfigure) {
            oneConfigure.fillColor = colorArray[index];
//            oneConfigure.shadeColors = @[[UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.8], [UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.6], [UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.4] ,[UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.2], [UIColor colorWithRed:255/255.0 green:50/255.0 blue:69/255.0 alpha:.1]];
        }];
    }];
    
//    NSArray<NSArray<NSNumber *> *> *valus = @[@[@2000, @10000, @5000], @[@22000, @60000, @8000], @[@32000, @65000, @80000], @[@26000, @30000, @6500], @[@23500, @10000, @4500], @[@6000, @80000, @4500], @[@60000, @88000, @90000], @[@60000, @88000, @90000], @[@60000, @88000, @90000], @[@60000, @88000, @90000], @[@60000, @88000, @90000]];
//    NSArray<NSString *> *titles = @[@"03-08", @"03-09", @"03-10", @"03-11", @"03-12", @"03-13", @"03-14", @"03-14", @"03-14", @"03-14", @"03-14", @"03-14"];
    
    kWEAK_SELF;
    // 配置数据
    [[chartBarView.dataSource.modelDataSource configNumberOfItems:^NSInteger{
        return weakSelf.valuse.count;
    }] configModelForItemAtIndex:^(id<HyChartBarModelProtocol>  _Nonnull model, NSInteger index) {
        model.text = weakSelf.titles[index];
        model.values = weakSelf.valuse[index];
        // 自定义数据
        NSDictionary *dict = @{@"colors" : colorArray, @"texts" : @[@"正常", @"异常", @"异常且严重"]};
        model.exData = dict;
    }];
    
    [chartBarView setNeedsRendering];
    
    return contentView;
}

- (IBAction)loadMore:(id)sender {
    AQJCVC *vc = [[AQJCVC alloc] init];
    [[WDGlobal getCurrentViewController].navigationController pushViewController:vc animated:NO];
}


#pragma mark - WKNavigationDelegate

// 网页加载完成后调用
//- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    // 准备要传递给网页的数据
//    //    NSArray *xData = @[@"衬衫", @"羊毛衫", @"雪纺衫", @"裤子", @"高跟鞋", @"袜子", @"连衣裙", @"外套"];
//    //    NSArray *yData = @[@5, @20, @36, @10, @15, @25, @30, @18];
////    NSLog(@"%@,%@",self.titles,self.values);
//    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
//    for (int i = 0; i < self.titles.count; i ++) {
//        NSString *item = self.titles[i];
//        NSMutableArray *values = [NSMutableArray arrayWithArray:self.valuse[i]];
//        [values insertObject:item atIndex:0];
//        [arr addObject:values];
//    }
//    NSMutableArray *titles = [NSMutableArray arrayWithArray:@[@"产品",@"正常",@"异常",@"异常且严重"]];
//    
//    [arr insertObject:titles atIndex:0];
//    // 将OC数组转换为JSON字符串
//    NSString *xJsonStr = [WDGlobal convertArrayToJsonString:self.titles];
//    NSString *yJsonStr = [WDGlobal convertArrayToJsonString:arr];
//    
//    if (xJsonStr && yJsonStr) {
//        // 构建JavaScript代码
//        NSString *jsCode = [NSString stringWithFormat:@"updateChart(%@, %@);", xJsonStr, yJsonStr];
//        
//        // 执行JavaScript代码
//        [webView evaluateJavaScript:jsCode completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//            if (error) {
//                NSLog(@"调用JavaScript失败: %@", error.localizedDescription);
//            } else {
//                NSLog(@"数据已成功传递到网页");
//            }
//        }];
//    } else {
//        NSLog(@"JSON转换失败");
//    }
//}
#pragma mark - WKNavigationDelegate（网页加载完成后传递数据）
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // 1. 准备图表数据（格式必须与dataset.source匹配）
    // 格式：[["产品名", "系列1名称", "系列2名称", ...], [产品1数据], [产品2数据], ...]
    
    NSMutableArray *sourceData = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < self.titles.count; i ++) {
        NSString *item = self.titles[i];
        NSMutableArray *values = [NSMutableArray arrayWithArray:self.valuse[i]];
        [values insertObject:item atIndex:0];
        [sourceData addObject:values];
    }
    NSMutableArray *titles = [NSMutableArray arrayWithArray:@[@"产品",@"正常",@"异常",@"异常且严重"]];
    
    [sourceData insertObject:titles atIndex:0];
    
    
//    NSArray *sourceData = @[
//        @[@"产品", @"2023年", @"2024年", @"2025年"], // 首行：列名（产品+系列名）
//        @[@"奶茶", @120, @150, @180],
//        @[@"咖啡", @90, @110, @130],
//        @[@"果汁", @80, @95, @110],
//        @[@"苏打水", @60, @85, @100],
//        @[@"茶饮料", @110, @130, @150]
//    ];
    
    // 2. 准备图例数据（与系列名对应）
    NSArray *legendData = @[@"正常",@"异常",@"异常且严重"];
    
    // 3. 转换为JSON字符串
    NSString *sourceJson = [WDGlobal convertArrayToJsonString:sourceData];
    NSString *legendJson = [WDGlobal convertArrayToJsonString:legendData];
    
    if (sourceJson && legendJson) {
        // 4. 调用JS方法更新图表
        NSString *jsCode = [NSString stringWithFormat:@"updateChart(%@, %@);", sourceJson, legendJson];
        [webView evaluateJavaScript:jsCode completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            if (error) {
                NSLog(@"更新失败：%@", error.localizedDescription);
            } else {
                NSLog(@"图表更新成功");
            }
        }];
    }
}

@end
